import { Container } from 'pixi.js'
import { loadBase64, imageToSprite } from '../util.js';

export class Obj {
    constructor(resource, stage) {
        this.resource = resource;
        this.stage = stage;

        this.layers = {
            0: [],
            1: [],
            2: [],
            3: [],
            4: [],
            5: [],
            6: [],
            7: [],
        };

        // 保存所有,Obj的Container
        this.containerArr = [];

    }

    /**
     * 
     * @param {object} Map
     * @public 
     */
    async load(Map) {
        // const resource = this.resource;

        // const result = new Set;
        // Object.keys(Map).forEach(key => {
        //     if (Number.isInteger(Number(key)) && Map[key].obj) {
        //         Object.values(Map[key].obj).forEach(v => {
        //             result.add(v.oS);
        //         })
        //     }
        // })
        // for (let oS of result) {
        //     await resource.load('Map/Obj', `./Map/Obj/${oS}.img.json`);
        // }
        await this.dealWithObj(Map)
    }

    /**
     * 
     * @param {number} layer 
     * @public
     */
    draw(layer) {
        
        const stage = this.stage
        const containerArr = this.containerArr;
        const layers = this.layers;

        const container = new Container();
        container.sortableChildren = true;
        container.zIndex = layer;
        layers[layer].forEach(sprite => {
            container.addChild(sprite);
        })
        stage.addChild(container);
        containerArr.push(container);
    }

    /**
     * @public
     */
    destroy() {
        const stage = this.stage
        const containerArr = this.containerArr;
        const layers = this.layers;
        
        containerArr.forEach(container => {
            stage.removeChild(container);
        })
        for (let i = 0; i < 7; i++) {
            layers[i].length = 0;
        }
        containerArr.length = 0;
    }

    /**
     * @private
     */
    async dealWithObj(Map) {
        for (let i = 0; i <= 7; i++) {
            if (Map[i].obj) {
                for (let item of Object.values(Map[i].obj)) {
                    const { oS, l0, l1, l2, x, y, zM, z } = item;
                    const { value, origin } = this.getGoalData(oS, l0, l1, l2);
                    let image = await loadBase64(value);
                    let sprite = imageToSprite(image);
                    sprite.x = x - origin.x;
                    sprite.y = y - origin.y;
                    sprite.zIndex = Number(z);
                    this.layers[i].push(sprite);
                }
            }
        }
    }

    /**
     * @private
     */
    getGoalData(oS, l0, l1, l2) {
        return this.resource.Content.Map.Obj[`${oS}`][l0][l1][l2][0];
    }
}